<template>
  <div class="search-details">
    <h1 class="search-title">
      <FileSearchOutlined />
      搜索 [ {{ keyword }} ] 结果：
    </h1>
    <a-spin :spinning="searching" tip="正在搜索" :indicator="indicator">
      <div class="cards">
<!--      <BlogCard v-for="blog in result.data"-->
<!--                :blog="blog" />-->
        <ArticleCard class="article-card"
                     v-for="blog in result.data"
                     :article="blog" />
        <a-empty description="无搜索结果"
                 class="empty"
                 v-if="result.data.length === 0" />
      <a-pagination v-model:current="result.current"
                    v-model:pageSize="result.pageSize"
                    :total="result.total"
                    class="pagination"
                    @change="pageChange"></a-pagination>
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {h, onMounted, ref, watch} from "vue";
import {apiGet} from "../../fentch";
import {message} from "ant-design-vue";
import BlogCard from "../../components/blog/search/BlogCard.vue";
import {FileSearchOutlined, LoadingOutlined} from "@ant-design/icons-vue";
import ArticleCard from "../../components/blog/list/ArticleCard.vue";

const route = useRoute()

// 搜索的关键词
const keyword = ref('')

// 搜索中
const searching = ref(false)

/**
 * 加载中自定义
 */
const indicator = h(LoadingOutlined, {
  style: {
    fontSize: '24px'
  },
  spin: true
})

/**
 * 检测动态变化的路由
 */
watch(() => route.query.q, (value, oldValue) => {
  keyword.value = value
  search()
})

/**
 * 搜索结果
 * @type {Ref<UnwrapRef<{current: number, total: number, data: *[], pageSize: number}>>}
 */
const result = ref({
  current: 0,
  pageSize: 10,
  total: 0,
  data: []
})

/**
 * 搜索请求 API
 * @param page
 */
const search = (page=1) => {
  searching.value = true
  apiGet(`/blogs/search/${keyword.value}?page=${page}`).then(res => {
    if (res.data.code === 0) {
      let data = res.data.data;
      let resultValue = result.value;
      resultValue.total = data.total;
      resultValue.current = data.current_page;
      resultValue.data = data.data;
      searching.value = false
      return
    }
    message.error(res.data.message)
  })
}

/**
 * 页面切换回调
 * @param e
 */
const pageChange = e => {
  search(e.page)
}

onMounted(() => {
  keyword.value = route.query.q
  // 加载后搜索
  search()
})
</script>

<style scoped>
.search-details {
  width: 1000px;
}

.cards {
  width: 1000px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.article-card {
  margin-top: 20px;
  width: 1000px;
}

.empty {
  margin-top: 20px;
}

.search-title {
  margin-top: 20px;
  margin-bottom: 0;
  padding: 0;
}

.pagination {
  margin-top: 20px;
}
</style>